package nl.Viewer.ViewManager.Models.DataStores;

import java.awt.Image;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;

import javax.imageio.ImageIO;

import nl.Viewer.SerializedObjects.DataObject;
import nl.Viewer.ViewManager.Objects.RendererHelperFunctions;

/**
 * An implementation of a DataStore to handle (single-tiled) image data
 * 
 * @author Jeroen Verschuur
 * 
 */

public class ImageDataStore extends DataStore {
   public ImageDataStore( DataObject dataObject ) {
      super( dataObject );
      int w = dataObject.getBounds().width;
      int h = dataObject.getBounds().height;

      currentData = new ImageDataObject( w, h, new int[ w * h ] );
   }

   public synchronized void addData( Object data, int resolution, int xPos, int yPos ) {
      // create an image from the data object
      try {
         byte[] imagedata = (byte[])data;

         Image image = ImageIO.read( new ByteArrayInputStream( imagedata ) );
         imagedata = null;
         int w = image.getWidth( null );
         int h = image.getHeight( null );

         int[] pixels = new int[ w * h ];

         PixelGrabber pg = new PixelGrabber( image, 0, 0, w, h, pixels, 0, w );
         pg.grabPixels();
         int[] mirror = new int[ w * h ];

         for( int y = 0; y < h; y++ ) {
            for( int x = 0; x < w; x++ ) {
               mirror[( ( h - y - 1 ) * w ) + x] = RendererHelperFunctions.convertPixel( pixels[( y * w ) + x] );
            }
         }
         pixels = null;
         image = null;
         //TODO: debug
         //System.out.println( "ImageDataStore: W = " + w + ", H = " + h );

         // we should always synchronize on the buffer to prevent access by for example the views
         synchronized( ( (ImageDataObject)currentData ) ) {
            ( (ImageDataObject)currentData ).data.rewind();
            ( (ImageDataObject)currentData ).data.put( mirror );
         }
         mirror = null;
      }
      catch( Exception e ) {
         System.out.println( "Error in creating image from byte[]: " + e );
         return;
      }
   }

}
